﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;

namespace WEEK13_上课演示
{
    public partial class Login : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                LoadCookie();
            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            string username = txtUserName.Text;
            string password = txtPassword.Text;

            string commandText =
                "SELECT username, password FROM Users WHERE username = '" + username + "'";
            using (SqlConnection connection = SqlHelper.GetConnection())
            {
                DataSet dataSet = SqlHelper.GetDataSetBySqlCommand(commandText, connection);

                if (dataSet.Tables[0].Rows.Count == 0)
                {
                    Response.Write("没有找到相应的用户");
                }
                else
                {
                    if (password == dataSet.Tables[0].Rows[0]["password"].ToString())
                    {
                        if (chkRememberPassword.Checked)
                        {
                            CreateCookie();
                        }


                        Session["username"] = username;
                        Response.Redirect("welcome.aspx");
                    }
                    else
                    {
                        Response.Write("密码错误");
                    }
                }
            }
        }

        private void LoadCookie()
        {
            if (Request.Cookies["account2"] != null)
            {
                txtUserName.Text = Request.Cookies["account2"]["username"];
                txtPassword.Text = Request.Cookies["account2"]["password"];
            }
        }

        private void CreateCookie()
        {
            if (Request.Cookies["account2"] == null)
            {
                var cookie = new HttpCookie("account2");
                cookie["username"] = txtUserName.Text;
                cookie["password"] = txtPassword.Text;
                cookie.Expires = DateTime.Now.AddMinutes(30);
                Response.Cookies.Add(cookie);
            }
        }
    }
}